package logic

import (
	"context"
	"errors"
	"home/model/cache"
	"home/model/mysql"
	"home/pkg"

	"home/homerpc/homerpc"
	"home/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForGetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForGetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForGetPasswordLogic {
	return &ForGetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品列表
func (l *ForGetPasswordLogic) ForGetPassword(in *homerpc.ForGetPasswordRequest) (*homerpc.ForGetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&users)
	if users.ID == 0 {
		return nil, errors.New("当前账号不存在，请更换")
	}

	result, _ := cache.Rdb.Get(l.ctx, "SendSms_"+in.Tel).Result()
	if result != in.SendSms {
		return nil, errors.New("验证码错误，请重新输入")
	}

	if users.Password == pkg.MD5(in.Password) {
		return nil, errors.New("密码和原密码相同，不允许修改")
	}

	if in.Password != in.NewPassword {

		return nil, errors.New("新密码和确认密码不一致，不允许修改")
	}

	users.Password = pkg.MD5(in.Password)

	mysql.DB.Debug().Updates(&users)

	return &homerpc.ForGetPasswordResponse{
		Uid: int64(users.ID),
	}, nil
}
